/*
 * Copyright (C) 2022, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: iaom <zhangpengfei@kylinos.cn>
 *
 */
#include "action.h"
#include <QDesktopServices>
#include <QDBusInterface>
#include <QProcess>
#include <QDebug>
#include <QUrl>

#define KYLIN_APP_MANAGER_NAME         "com.kylin.AppManager"
#define KYLIN_APP_MANAGER_PATH         "/com/kylin/AppManager"
#define KYLIN_APP_MANAGER_INTERFACE    "com.kylin.AppManager"
using namespace Notify;
class Notify::ActionPrivate {
public:
    struct actionInfo
    {
        actionInfo(const QString &action, const QString &displayName) {
            m_action = action;
            m_displayName = displayName;
        }
        QString m_action;
        QString m_displayName;
    };
    QString m_url;
    QList<actionInfo> m_actions;
    void addAction(const QString &action, const QString &displayName) {
        m_actions.append(actionInfo(action, displayName));
    }
};

Action::Action(): d(new ActionPrivate)
{
}

Action::Action(const Action &other): d(new ActionPrivate(*other.d))
{
}

Action::~Action()
{
}

Action &Action::operator =(const Action &other)
{
    *d = *other.d;
    return *this;
}

void Action::setUrl(const QString &url)
{
    d->m_url = url;
}

QString Action::getUrl() const
{
    return d->m_url;
}

void Action::addAction(const QString &action, const QString &displayName)
{
    d->addAction(action, displayName);
}

bool Action::executeDefaultAction()
{
    if(!d->m_actions.isEmpty()) {
        QProcess p;
        if (!p.startDetached(d->m_actions.at(0).m_action)) {
            qWarning()<<"Action execute failed:" << d->m_actions.at(0).m_action;
        }
        return true;
    } else if(!d->m_url.isEmpty()) {
        QDBusInterface appManagerIface(KYLIN_APP_MANAGER_NAME,
                                       KYLIN_APP_MANAGER_PATH,
                                       KYLIN_APP_MANAGER_INTERFACE,
                                       QDBusConnection::sessionBus());
        if (appManagerIface.isValid()) {
            appManagerIface.call("LaunchDefaultAppWithUrl",d->m_url);
        } else {
            qWarning()<<"App manager Iface init failed during Action execution!";
            QDesktopServices::openUrl(QUrl::fromLocalFile(d->m_url));
        }
        return true;
    } else {
        return false;
    }
}
